package cool.doudou.doudada.cipher.algorithm.util;

import cool.doudou.doudada.cipher.algorithm.enums.SignAlgorithm;

import java.nio.charset.StandardCharsets;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;

/**
 * 签名、验证
 *
 * @author jiangcs
 * @since 2022/08/24
 */
public class SignatureUtil {
    /**
     * 签名
     *
     * @param signAlgorithm 签名算法
     * @param plaintext     明文
     * @param privateKey    密钥
     * @return 密文字节数组
     */
    public static byte[] sign(SignAlgorithm signAlgorithm, String plaintext, PrivateKey privateKey) {
        try {
            // 签名值
            Signature signature = Signature.getInstance(signAlgorithm.name());
            signature.initSign(privateKey);
            signature.update(plaintext.getBytes(StandardCharsets.UTF_8));
            return signature.sign();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 验签
     *
     * @param signAlgorithm  签名算法
     * @param ciphertext     密文
     * @param publicKey      公钥
     * @param signatureBytes 待验证字节数组
     * @return true-成功；false-失败
     */
    public static boolean verify(SignAlgorithm signAlgorithm, String ciphertext, PublicKey publicKey, byte[] signatureBytes) {
        try {
            // 签名值
            Signature signature = Signature.getInstance(signAlgorithm.name());
            signature.initVerify(publicKey);
            signature.update(ciphertext.getBytes(StandardCharsets.UTF_8));
            return signature.verify(signatureBytes);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
